﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections ;

using YT.Commons;
using YT.DB;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using YT.Modules;

namespace YT.XH.IgE
{
    public partial class frmIgEdetectInfo : Form
    {
        private FormStatus mfrmStatus = new FormStatus();
        private long mlngRecID = 0;
        private bool mBlnAlreadyLoad = false;
        private bool mblnPosted = false;
        private DBAccess mdbcon = new DBAccess(false, false);
        public frmIgEdetectInfo(FormStatus frmStatus)
        {
            InitializeComponent();
            mfrmStatus = frmStatus;
        }

        private struct ExcelODValue
        {
            public string Row;
            public string Col;
            public double dblValue;
        }

        private FormType mFromType = new FormType();
        private FormType MFromType
        {
            get
            {
                using (DBAccess dbcon = new DBAccess(false, false))
                {
                    try
                    {
                        string strSQL = "Select DetectStatus From IgEDetectHdr where RecID='" + mlngRecID + "' and posted=1";
                        DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                        if (drRow != null)
                        {
                            return FormType.Finish;
                        }
                        else
                        {
                            return mFromType;
                        }
                    }
                    catch (Exception ex)
                    {
                        return mFromType;
                    }
                }
            }
            set { mFromType = value;
                    InitControl();
            }
        }
        
        private enum FormType
        {
            /// <summary>
            /// 添加新检查
            /// </summary>
            AddNew=0,

            /// <summary>
            /// 设置面板
            /// </summary>
            SetGrid ,

            /// <summary>
            /// 导入EXCEL检测数据
            /// </summary>
            InputFromExcel,

            /// <summary>
            /// 选择患者
            /// </summary>
            SelectSickPerson,
            
            /// <summary>
            /// 已经拥有标准方程
            /// </summary>
            WithFormula,
            
            /// <summary>
            /// 完结
            /// </summary>
            Finish,
        }

        private FormulaType mFormulaType = new FormulaType();

      

        public bool ShowData(long lngRecID, FormulaType formulaType)
        {
            mlngRecID = lngRecID;
            mFormulaType = formulaType;
            mblnPosted =CvtFunc.ToBoolean(mdbcon.GetValue ("select posted from IgEDetectHdr Where RecID='"+ lngRecID +"'"));
                  
            if (lngRecID > 0)
            {   
                ShowHdrInfo();
                //ImportODValue(null);
                ShowDetailInfo();
            }
            InitControl();     
            this.ShowDialog(); 
            return true;
        }

        private void InitControl()
        {
            this.btnSelectFormulaFromDB.Visible = false;
            this.btnGenFormula.Visible = false;
            this.btnExcel.Visible = false;            
            this.btnSelPerson.Visible = false;
            this.btnSelectFormulaFromDB.Visible = false;
            this.btnGenFormula.Visible = false;
            this.btnSetCheckPanel.Visible = false;
            this.grpSize.Enabled = false;
            this.btnExcel.Visible = true;
            this.btnPreview.Visible = true;
            if (MFromType== FormType.AddNew)
            {
                txtCheckName.Text = SysVar.UserName;
                SetDetectID();
                grpSize.Enabled = true ;                
                this.btnSetCheckPanel.Visible = true ;
                this.btnExcel.Visible =true ;
            }
            if (MFromType == FormType.SetGrid)
            {
                this.btnSelPerson.Visible = true;                
            }
            else if (MFromType == FormType.InputFromExcel)
            {
                this.btnSelPerson.Visible = true;
                this.btnSelectFormulaFromDB.Visible = true;
                this.btnGenFormula.Visible = true;
                this.btnSetCheckPanel.Visible = false;
                this.txtDetectID.Enabled = false;
                if (txtStandardFormulaRecID.Text != "" || txtStandardFormulaRecID.Text != "0")
                {
                    btnPosted.Visible = true;    
                }
            }
            else if (MFromType == FormType.WithFormula)
            {
                btnPosted.Enabled = true;    
            }
            else if (MFromType == FormType.Finish)
            {
                this.btnExcel.Visible = false;
                txtDetectID.Enabled = false;
                txtCheckName.Enabled = false;
                btnSave.Visible = false;
                dtpDate.Enabled = false;
                toolStripSeparator1.Visible = false;
                toolStripSeparator2.Visible = false;
                toolStripSeparator3.Visible = false;
                this.btnSelPerson.Visible = true;
            }
        }

        private void SetDetectID()
        {

            string strMaxValue = DataFunctions.GetFieldValue("IgEDetectHdr", "max(DetectID) as SickID ", " 1=1 ");
            string strMaxValueDate = string.Empty;
            int intMaxVauleSeqNo = 0;
            if (strMaxValue == "")
            {
                strMaxValueDate = DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Month.ToString().PadLeft(2, '0') + DateTime.Now.Date.Day.ToString().PadLeft(2, '0') + "001";
                txtDetectID.Text = strMaxValueDate;
            }
            else
            {
                strMaxValueDate = strMaxValue.Substring(0, 8);
                string strCurDate = DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Month.ToString().PadLeft(2, '0') + DateTime.Now.Date.Day.ToString().PadLeft(2, '0');
                if (strMaxValueDate == strCurDate)
                {
                    intMaxVauleSeqNo = CvtFunc.ToInt(strMaxValue.Substring(8, 3));
                    intMaxVauleSeqNo++;
                    txtDetectID.Text = strMaxValueDate + CvtFunc.ToString(intMaxVauleSeqNo).PadLeft(3, '0');
                }
                else
                {
                    strMaxValueDate = DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Month.ToString().PadLeft(2, '0') + DateTime.Now.Date.Day.ToString().PadLeft(2, '0') + "001";
                    txtDetectID.Text = strMaxValueDate;
                }
            }
        }

        private void AddControlToPanel()
        {
            int intRows = CvtFunc.ToInt(txtRow.Text);
            int intCols = CvtFunc.ToInt(txtCol.Text);
            if (mBlnAlreadyLoad) return;
            for (int i = 0; i < intRows; i++)
            {
                for (int j = 0; j < intCols; j++)
                {
                    frmIgeDetectControl frmControl = new frmIgeDetectControl();
                    frmControl.Name = i.ToString() + j.ToString();
                    frmControl.TopMost = false;
                    frmControl.TopLevel = false;
                    frmControl.Top = 0;
                    frmControl.Left = 0;
                    frmControl.Visible = true;
                    tlpDetail.Controls.Add(frmControl, j, i);
                }
            }
            tlpDetail.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;

            for (int i = 0; i < intRows; i++)
            {
                Label lblRow = new Label ();                
                lblRow.Text = (i+1).ToString();
                lblRow.Text = BaseFunctions.SetCharRow(lblRow.Text);
                tlpRows.Controls.Add(lblRow);
            }

            for (int j = 0; j < intCols; j++)
            {
                Label lblRow = new Label();
                lblRow.Text = (j + 1).ToString();
                tlpColumns.Controls.Add(lblRow);
            }
        }

        private void ImportODValue(ArrayList listODValue)
        {
            int intRows= CvtFunc.ToInt ( txtRow.Text );
            int intCols = CvtFunc.ToInt ( txtCol.Text );
            if (mBlnAlreadyLoad) return;
           
            for (int i = 0; i < intRows; i++)
            {
                for (int j = 0; j < intCols; j++)
                {
                    Control con = tlpDetail.GetControlFromPosition(j, i);
                    frmIgeDetectControl frmControl = con as frmIgeDetectControl;

                    ExcelODValue ODValue = new ExcelODValue();
                    ODValue.Col = j.ToString();
                    ODValue.Row = i.ToString();
                    if (!GetODValue(listODValue, ref ODValue)) return;
                    frmControl.txtODValue.Text = Math.Round(ODValue.dblValue, 4).ToString();
                    frmControl.txtDilutionFactor.Text = "100";
                }
            }
            tlpDetail.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            
        }

        private bool GetODValue(ArrayList listODValue, ref ExcelODValue ODValue)
        {
            foreach (ExcelODValue tODValue in listODValue)
            {
                if (tODValue.Row == ODValue.Row && tODValue.Col == ODValue.Col)
                {
                    ODValue.dblValue = tODValue.dblValue;
                    return true;
                    break;
                }
            }
            return false;
        }

        private void ShowHdrInfo()
        {
            string strSQL = "";
            strSQL ="select * from IgEDetectHdr where RecID='"+ mlngRecID +"'";             
            DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
            if (drHdr != null)
            {
                txtRow.Text = CvtFunc.ToInt(drHdr["Rows"]).ToString() ;
                txtCol.Text = CvtFunc.ToInt(drHdr["Cols"]).ToString() ;
                txtCheckName.Text = CvtFunc.ToString(drHdr["CheckName"]);
                txtDetectID.Text = CvtFunc.ToString(drHdr["DetectID"]);
                txtParaR.Text =   CvtFunc.ToDouble( CvtFunc.ToString (  drHdr["ParaR"]))==0? "": CvtFunc.ToString ( drHdr["ParaR"]);
                txtStandardFormula.Text = CvtFunc.ToString(drHdr["StandardFormula"]);
                txtRemark.Text = CvtFunc.ToString(drHdr["Remark"]);
                txtStandardFormulaRecID.Text = CvtFunc.ToLong(drHdr["StandardFormulaRecID"]) == 0 ? "" : CvtFunc.ToString(drHdr["StandardFormulaRecID"]);
                MFromType = (FormType)CvtFunc.ToInt(drHdr["DetectStatus"]); 
                InittlpDetail();
                AddControlToPanel();
            }
        }

        private void ShowDetailInfo()
        {
            string strSQL = "";
            int intRow = 0;
            int intCol = 0;
            strSQL ="select * from IgEDetectDetail Where HdrRecID='"+ mlngRecID +"'";
            DataTable dtDtl = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drDtl in dtDtl.Rows)
            {
                intRow =CvtFunc.ToInt ( drDtl["Rows"]);
                intCol =CvtFunc.ToInt ( drDtl["Cols"]);
                Control con = tlpDetail.GetControlFromPosition(intCol , intRow );
                frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                
                frmControl.txtCalValue.Text =CvtFunc.ToString(drDtl["CalValue"]);
                frmControl.txtODValue.Text = BaseFunctions.FormatNumeric ( CvtFunc.ToString(drDtl["ODValue"]),"n.5");
                frmControl.txtDetectLabel.Text =   CvtFunc.ToString(drDtl["DetectLabel"]);
                frmControl.txtRecID.Text = CvtFunc.ToString(drDtl["RecID"]);
                frmControl.txtSickRecID.Text = CvtFunc.ToString(drDtl["SickPersonID"]);
                frmControl.txtDilutionFactor.Text = CvtFunc.ToDouble(drDtl["DilutionFactor"]).ToString() ;
                frmControl.chkIsStandardFormula.Checked = CvtFunc.ToBoolean(drDtl["IsStandardFormula"]);
                if (frmControl.chkIsStandardFormula.Checked)
                {
                    
                }
              
                
            }
        }

        private bool Update()
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                if (!ValidCheck()) return false;
                if (mlngRecID <= 0)
                {
                    string strSQL = @"Insert Into IgEDetectHdr (DetectID,CheckName,CheckDate,DetectStatus,StandardFormulaRecID,StandardFormula,ParaR,Remark,FormulaType,Rows,Cols  )
                              Values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')";
                    strSQL = string.Format(strSQL, txtDetectID.Text
                                                    , txtCheckName.Text
                                                    , dtpDate.Value
                                                    ,(int)MFromType
                                                    , CvtFunc.ToLong(  txtStandardFormulaRecID.Text)
                                                    , BaseFunctions.SpecialCharDeal(txtStandardFormula.Text)
                                                    , CvtFunc.ToDouble(  txtParaR.Text)
                                                    , BaseFunctions.SpecialCharDeal(txtRemark.Text)
                                                    , mFormulaType
                                                    , CvtFunc.ToInt(txtRow.Text)
                    

                                                    , CvtFunc.ToInt(txtCol.Text));
                    strSQL = strSQL + ";Select @@identity";
                    mlngRecID = CvtFunc.ToLong(dbcon.GetObjectValue(strSQL));
                }
                else
                {
                    string strSQL = @"Update IgEDetectHdr set DetectID='{0}'
                                                                ,CheckName='{1}'
                                                                ,CheckDate='{2}'
                                                                ,StandardFormulaRecID='{3}'
                                                                ,StandardFormula='{4}'
                                                                ,ParaR='{5}'
                                                                ,Remark='{6}'
                                                                ,FormulaType='{7}'
                                                                ,Rows='{8}'
                                                                ,Cols='{9}'
                                                                ,DetectStatus='{10}'                
                                                                Where RecID='{11}'";

                        strSQL = string.Format(strSQL, txtDetectID.Text
                                                    , txtCheckName.Text
                                                    , dtpDate.Value
                                                    , CvtFunc.ToLong  ( txtStandardFormulaRecID.Text)
                                                    , BaseFunctions.SpecialCharDeal(txtStandardFormula.Text)
                                                    , CvtFunc.ToDouble( txtParaR.Text)
                                                    , BaseFunctions.SpecialCharDeal(txtRemark.Text)
                                                    , mFormulaType
                                                    , CvtFunc.ToInt(txtRow.Text)
                                                    , CvtFunc.ToInt(txtCol.Text)
                                                    , (int)MFromType
                                                    , mlngRecID );
                        dbcon.ExecuteSql(strSQL); 
                }
            }
            return true;
        }

        private bool VaildCheckStandardFormula()
        {
            if (txtStandardFormula.Text == "")
            {
                MessageBox.Show("特异性IgG4标准曲线不能为空！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;

            }
            return true;
        }

        private bool ValidCheck()
        {
            if (txtDetectID.Text == "")
            {
                MessageBox.Show("检测编号不能为空。", SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
            return true;
        }

        private void UpdateStandardFormula()
        {
            if (!VaildCheckStandardFormula()) return;
            string strSQL = "select count(*) from IgEStandardFormula where RecID='"+ txtStandardFormulaRecID.Text   +"'";
            if (CvtFunc.ToInt(mdbcon.GetValue(strSQL)) <=0)
            {
                strSQL = @"Insert Into IgEStandardFormula ( StandardFormula,Remark,GenerateDate,DetectID,FormulaType,ParaR )
                           Values ('{0}','{1}',{2},'{3}','{4}','{5}');
                           Select @@identity";
                strSQL = string.Format(strSQL, txtStandardFormula.Text
                                                , ""
                                                , "getdate()"
                                                , txtDetectID.Text
                                                , mFormulaType
                                                , CvtFunc.ToDouble(txtParaR.Text)
                                                );

                txtStandardFormulaRecID.Text = CvtFunc.ToString(mdbcon.GetObjectValue(strSQL));    
                strSQL =" Update IgEDetectHdr set StandardFormulaRecID='"+  txtStandardFormulaRecID.Text  +"'";
                mdbcon.ExecuteSql( strSQL ); 
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            if (!checkGridRowCol()) return;
            if (grpSize.Enabled)
            {
                btnSetCheckPanel_Click(this.btnSetCheckPanel, new EventArgs());
            }
            if (grpSize.Enabled) return;
            ArrayList listODValue = new ArrayList();
            this.Cursor = Cursors.WaitCursor;
            if (!ImportDataFromExcel(ref listODValue)) return ;

            //if (MFromType == FormType.AddNew)
            //{
            //    InittlpDetail();
            //    AddControlToPanel();
            //    InitControl();
            //}
            if (Update())
            {
                ImportODValue(listODValue);
                Calculateformula();
            }
             
            grpSize.Enabled = false;
            mBlnAlreadyLoad = true;

            MFromType = FormType.InputFromExcel; 
            this.Cursor = Cursors.Default;
        }

        private void Calculateformula()
        {
            ArrayList lstFormula = new ArrayList ();
            for (int i = 0; i <= tlpDetail.RowCount -1 ; i++)
            {
                for (int j = 0; j <=  tlpDetail.ColumnCount -1 ; j++)
                {
                    Control con = tlpDetail.GetControlFromPosition(j, i);
                    frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                    if (frmControl.chkIsStandardFormula.Checked)
                    {
                        lstFormula.Add( new PointF( CvtFunc.ToFloat(frmControl.txtODValue.Text), CvtFunc.ToFloat(frmControl.txtCalValue.Text))); 
                    }                    
                }
            }
            string strFormula ="";
            double dblParaR =0 ;
            if (lstFormula.Count > 0)
            {
                if (DataFunctions.GetLineFormula(lstFormula, ref strFormula, ref dblParaR))
                {
                    txtStandardFormula.Text = strFormula;
                    txtParaR.Text = dblParaR.ToString();
                }
            }
        }

        private bool checkGridRowCol()
        {
            if (CvtFunc.ToInt(txtRow.Text) <= 0 || CvtFunc.ToInt(txtRow.Text) > 8)
            {
                MessageBox.Show("行数超出范围，行数只能位于 1-8 之间", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRow.Focus();
                return false;
            }
            if (CvtFunc.ToInt(txtRow.Text) <= 0 || CvtFunc.ToInt(txtRow.Text) > 12)
            {
                MessageBox.Show("列数超出范围，行数只能位于 1-12 之间", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCol.Focus();
                return false;
            }
            return true;
        }

        private void InittlpDetail()
        {            
            tlpDetail.ColumnCount = 0;
            tlpDetail.RowCount = 0;

            int intRows = CvtFunc.ToInt(txtRow.Text);
            int intCols = CvtFunc.ToInt(txtCol.Text);

            tlpDetail.ColumnCount = intCols;
            tlpDetail.RowCount = intRows;

            tlpColumns.ColumnCount = intCols;
            tlpRows.RowCount = intRows;
        }

        private void btnGenFormula_Click(object sender, EventArgs e)
        {
            int intRows = CvtFunc.ToInt(txtRow.Text);
            int intCols = CvtFunc.ToInt(txtCol.Text);

            for (int i = 0; i < intRows; i++)
            {
                for (int j = 0; j < intCols; j++)
                {
                    Control con = tlpDetail.GetControlFromPosition( j,i ); 
                    frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                    if (frmControl != null)
                    {
                        frmControl.chkIsStandardFormula.Visible = true;
                    }                    
                }
            }
            foreach (ToolStripItem tsb in this.toolStrip1.Items)
            {                
                tsb.Enabled = false;
            }
            btnFinishSelect.Visible = true;
            btnFinishSelect.Enabled = true;

          
        }

        private void btnFinishSelect_Click(object sender, EventArgs e)
        {
            foreach (ToolStripItem tsb in this.toolStrip1.Items)
            {
                tsb.Enabled = true ;
            }
            btnFinishSelect.Visible = false;
            int intRows = CvtFunc.ToInt(txtRow.Text);
            int intCols = CvtFunc.ToInt(txtCol.Text);
            for (int i = 0; i < intRows; i++)
            {
                for (int j = 0; j < intCols; j++)
                {
                    Control con = tlpDetail.GetControlFromPosition(j, i);
                    frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                    if (frmControl != null)
                    {
                        frmControl.chkIsStandardFormula.Visible = false ;
                    }
                }
            }
            Calculateformula();
            UpdateAllDetail();
            ShowDetailInfo(); 
        }

        private void frmIgEdetectInfo_Load(object sender, EventArgs e)
        {
            this.MinimumSize = this.Size;
            this.Text = SysVar.CurrentMenuInfo.strMenuName;
           
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出吗？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                this.Close(); 
            }
        }


        private bool ImportDataFromExcel(ref ArrayList lstODValue)
        {
            string strFieldName ="";
            Properties.Settings config = Properties.Settings.Default;
            if (config.InitExcelPath != "")
            {
                OFDSelectExcel.InitialDirectory =  config.InitExcelPath   ;
            }
            OFDSelectExcel.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx";
            OFDSelectExcel.Title = "检测EXCEL文件的导入";
            OFDSelectExcel.ShowDialog(); 
            if (!OFDSelectExcel.CheckFileExists) return false ;
            if (!OFDSelectExcel.CheckPathExists) return false ;

            strFieldName = OFDSelectExcel.FileName;
            
            if (strFieldName == "") { this.Cursor = Cursors.Default; return false; }
            config.InitExcelPath = System.IO.Path.GetDirectoryName(strFieldName); ;
            Excel.Application xlApplication = new Excel.Application();
            Excel.Workbooks xlBooks = (Excel.Workbooks)xlApplication.Workbooks;
            xlBooks = (Excel.Workbooks)xlApplication.Workbooks;
            Excel._Workbook ThisWorkbook = (Excel._Workbook)(xlBooks.Open( strFieldName));
            Excel.Worksheet xlSheet = (Excel.Worksheet)ThisWorkbook.Sheets[1];
            string strSQL = string.Empty;
            
            try
            {
                int intRow = 1;
                int intCol = 1;
                
                this.btnExcel.Enabled = false;

                for (intRow = 1; intRow <= 8; intRow++)
                {
                    for (intCol = 1; intCol <= 12; intCol++)
                    {
                        Excel.Range cell = null;
                        cell = (Excel.Range)xlSheet.Cells[intRow, intCol];
                        string strTmp = cell.Value2.ToString();
                        ExcelODValue ODValue = new ExcelODValue();
                        ODValue.Col = (intCol-1).ToString();
                        ODValue.Row = (intRow-1).ToString();
                        ODValue.dblValue = CvtFunc.ToDouble(strTmp);
                        lstODValue.Add(ODValue); 
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        private void btnSelectFormulaFromDB_Click(object sender, EventArgs e)
        {
            if (txtStandardFormulaRecID.Text != ""
                 || CvtFunc.ToInt(txtStandardFormulaRecID.Text) > 0)
            {
                if (MessageBox.Show("曲线方程已经存在，您是否要替换原来曲线方程？", "确认",  MessageBoxButtons.YesNo , MessageBoxIcon.Question )== System.Windows.Forms.DialogResult.No )
                {
                    return ;
                }
            }
            string strSQL = "SELECT RecID,StandardFormula as 曲线方程,ParaR as 方差, Remark as 备注,GenerateDate as 产生日期 FROM IgEStandardFormula where FormulaType='"+ mFormulaType +"'";
            frmLookUp_Cust frmlookup = new frmLookUp_Cust(mdbcon, strSQL, "患者选择", "", "SickRecID");
            frmlookup.ShowDialog();
            if (frmlookup.HaveReturnValue)
            {
                txtStandardFormula.Text = frmlookup.GetReturnValue("StandardFormula");
                txtParaR.Text = frmlookup.GetReturnValue("ParaR");
                txtStandardFormulaRecID.Text = frmlookup.GetReturnValue("RecID");

                strSQL ="Update IgEDetectDetail Set IsStandardFormula=0 where IsStandardFormula=1 and HdrRecID='"+ mlngRecID +"'";
                mdbcon.ExecuteSql( strSQL );
               
                ShowDetailInfo(); 
                if (Update())
                {
                    UpdateAllDetail();
                    UpdateStandardFormula();
                   
                }
                 
            }            
        }

        private void btnPosted_Click(object sender, EventArgs e)
        {
            if (!VaildCheckStandardFormula()) return;
            if (MessageBox.Show("您确定 审核并提交此检测结果?", "提交检测结果", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (Update())
                {
                    UpdateStandardFormula();
                    UpdateAllDetail();
                    UpdateToHistory();
                    string strSQL = "";
                    strSQL = "Update IgEDetectHdr Set Posted=1 Where RecID='" + mlngRecID + "' ";
                    mdbcon.ExecuteSql(strSQL);
                    MessageBox.Show("审核成功！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
        }


        private bool UpdateToHistory()
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                try
                {
                    int intRows = CvtFunc.ToInt(txtRow.Text);
                    int intCols = CvtFunc.ToInt(txtCol.Text);
                    for (int i = 0; i < intRows; i++)
                    {
                        for (int j = 0; j < intCols; j++)
                        {
                            Control con = tlpDetail.GetControlFromPosition(j, i);
                            frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                            if (frmControl != null)
                            {
                                string strSQL = "update IgETreatHistory Set {0}={1},{3}='{4}' Where {2}=1 and ({0}='' or {0}=0) and SickRecID='" + frmControl.txtSickRecID.Text + "' ";
                                if (mFormulaType == FormulaType.TotalIgG4)
                                {
                                    strSQL = string.Format(strSQL, "TotalIgG4Value"
                                                                    , CvtFunc.ToDouble(frmControl.txtCalValue.Text)
                                                                    , "NeedTotalIgG4"
                                                                    , "TotalIgG4ID"
                                                                    , CvtFunc.ToString(frmControl.txtDetectLabel.Text)
                                                                    );
                                }
                                else if (mFormulaType == FormulaType.IgE)
                                {
                                    strSQL = string.Format(strSQL, "IgEValue"
                                                                    , CvtFunc.ToDouble(frmControl.txtCalValue.Text)
                                                                    , "NeedIgE"
                                                                    , "IgEID"
                                                                    , CvtFunc.ToString(frmControl.txtDetectLabel.Text)
                                                                    );
                                }
                                else if (mFormulaType == FormulaType.IgG4)
                                {
                                    strSQL = string.Format(strSQL, "IgG4Value"
                                                                    , CvtFunc.ToDouble(frmControl.txtCalValue.Text)
                                                                    , "NeedIgG4"
                                                                    , "IgG4ID"
                                                                    , CvtFunc.ToString(frmControl.txtDetectLabel.Text)
                                                                    );
                                }
                                else
                                {
                                    return false ;
                                };
                                dbcon.ExecuteSql(strSQL); 
                            }
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Update())
            {
               
                    UpdateAllDetail();
                    UpdateStandardFormula();
                    this.Close();
                
            }
        }

        private bool UpdateDetail(frmIgeDetectControl frmcontrol,int intRow, int intCol)
        {
            string strSQL = "";
           
                if (frmcontrol.chkIsStandardFormula.Checked)
                {

                }
                else
                {
                    frmcontrol.txtCalValue.Text = CvtFunc.ToString ( CvtFunc.ToDouble (frmcontrol.txtDilutionFactor.Text) *  Math.Round(DataFunctions.GetCalValueFromFormula(CvtFunc.ToDouble(frmcontrol.txtODValue.Text), txtStandardFormula.Text), 4));
                }
           
            
                if (CvtFunc.ToLong(frmcontrol.txtRecID.Text) > 0)
                {
                    strSQL = @"Update IgEDetectDetail Set Rows='{0}'
                                                      ,Cols='{1}'
                                                      ,SickPersonID='{2}'
                                                      ,DetectLabel='{3}'
                                                      ,ODValue='{4}'
                                                      ,CalValue='{5}'
                                                      ,IsStandardFormula='{6}' 
                                                      ,DilutionFactor='{7}'
                              Where RecID='{8}'";
                    strSQL = string.Format(strSQL, intRow
                                                   , intCol
                                                   , frmcontrol.txtSickRecID.Text
                                                   , frmcontrol.txtDetectLabel.Text
                                                   , CvtFunc.ToDouble ( frmcontrol.txtODValue.Text)
                                                   , CvtFunc.ToDouble(  frmcontrol.txtCalValue.Text)
                                                   , frmcontrol.chkIsStandardFormula.Checked ? 1 : 0
                                                   , CvtFunc.ToDouble ( frmcontrol.txtDilutionFactor.Text )
                                                   , frmcontrol.txtRecID.Text);
                    mdbcon.ExecuteSql(strSQL);
                }
                else
                {
                    strSQL = @" Insert Into IgEDetectDetail (HdrRecID,Rows,Cols,SickPersonID,DetectLabel,ODValue,CalValue,IsStandardFormula,DilutionFactor)
                        Values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}') ";
                    strSQL = string.Format(strSQL, mlngRecID
                                                    , intRow
                                                    , intCol
                                                    , frmcontrol.txtSickRecID.Text
                                                    , frmcontrol.txtDetectLabel.Text
                                                    , CvtFunc.ToDouble(frmcontrol.txtODValue.Text)
                                                    , CvtFunc.ToDouble(frmcontrol.txtCalValue.Text)
                                                    , frmcontrol.chkIsStandardFormula.Checked ? 1 : 0
                                                    , CvtFunc.ToDouble ( frmcontrol.txtDilutionFactor.Text )            
                                                        );
                    strSQL += ";select @@identity";
                    frmcontrol.txtRecID.Text = CvtFunc.ToString(mdbcon.GetObjectValue(strSQL));

                }
            
            return true;
        }

        private void btnSelPerson_Click(object sender, EventArgs e)
        {
            if (!mblnPosted)
            {
                if (mlngRecID == 0)
                {
                    if (!Update()) return;
                }
                UpdateAllDetail();
            }
            
            frmIgESetDetectLabel frmSetPerson = new frmIgESetDetectLabel(mlngRecID.ToString());
            frmSetPerson.mFormulaType = mFormulaType;
            frmSetPerson.StartPosition = FormStartPosition.CenterParent;
            frmSetPerson.ShowDialog();
            ShowDetailInfo();
            UpdateAllDetail();
            ShowDetailInfo();
        }

        private void UpdateAllDetail()
        {
            int intRows = CvtFunc.ToInt(txtRow.Text);
            int intCols = CvtFunc.ToInt(txtCol.Text);
            for (int i = 0; i < intRows; i++)
            {
                for (int j = 0; j < intCols; j++)
                {
                    Control con = tlpDetail.GetControlFromPosition(j, i);
                    frmIgeDetectControl frmControl = con as frmIgeDetectControl;
                    if (frmControl != null)
                    {
                        UpdateDetail(frmControl, i, j);
                    }
                }
            }
        }

        private void btnSetCheckPanel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定检测版规格是 " + txtRow.Text + "  X  " + txtCol.Text + " ? ", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                InittlpDetail();
                AddControlToPanel();
                InitControl();
                MFromType = FormType.SetGrid;
            }
        }


        private void PrintRpt(DBAccess dbcon,string strHdrRecID,bool blnWithAll)
        {
            if (Update())
            {
                UpdateAllDetail();
                UpdateStandardFormula();
            }
            else
            {
                return;
            }
            DataFunctions.DelTemporyTable(dbcon, "#tmpDetectInfo");
            string strSQL = @"Create Table #tmpDetectInfo ( 
                             RecID int identity(1,1), 
                             RowSeqNo char not null default '',
                             DetectID char(20) not null default '',
                             CheckName char(20) not null default '',
                             CheckDate DateTime NULL,
                             StandardFormula varchar(150) not null default '',
                             ParaR decimal(18,8) default 0,                            
                             Remark varchar(500) not null default '',
                            ";
            for (int iCol = 1; iCol <= 12;iCol ++ )
            {
                strSQL += @" ID{0} varchar(20) not null default '',
                            OD{0} decimal(18,6) not null default 0,
                            CalValue{0} decimal(18,6) not null default 0,
                            SickPersonName{0} varchar(40) not null default '',
                            SickPersonID{0} char(16) not null default '',
                            DilutionFactor{0}  decimal(18,2) null,";
                strSQL = string.Format(strSQL, iCol.ToString());
            }

            strSQL += " DetectRecID int  not null default 0 )";            
            dbcon.ExecuteSql(strSQL);

            int iRowCount = CvtFunc.ToInt ( dbcon.GetValue ("select max(Rows) From IgEDetectDetail where HdrRecID='"+ strHdrRecID +"'"))+1;
            for (int iRow = 1; iRow <= iRowCount; iRow++)
            {
                string strCharRow = BaseFunctions.SetCharRow(iRow.ToString());
                strSQL = @"Insert Into #tmpDetectInfo (RowSeqNo,DetectRecID,DetectID,CheckName,CheckDate,StandardFormula,ParaR,Remark)
                      Select '{1}',RecID,DetectID,CheckName,CheckDate,StandardFormula,ParaR,Remark From IgEDetectHdr Where RecID='{0}'";
                strSQL = string.Format(strSQL, strHdrRecID, strCharRow);
                dbcon.ExecuteSql(strSQL);

                for (int iCol = 1; iCol <= 12; iCol++)
                {
                  
                    strSQL = @"Update #tmpDetectInfo Set 
                               ID{1}=B.DetectLabel ,
                               OD{1}=B.ODValue,
                               CalValue{1}=B.CalValue,
                               SickPersonID{1}=B.SickPersonID,  
                               DilutionFactor{1}=B.DilutionFactor                  
                               From IgEDetectDetail B Where #tmpDetectInfo.DetectRecID=B.HdrRecID and B.HdrRecID='{0}' and Cols='{2}' and Rows='{3}' and RowSeqNo='{4}'";
                    strSQL = string.Format(strSQL, strHdrRecID, iCol, iCol - 1, iRow - 1, strCharRow);
                    dbcon.ExecuteSql(strSQL);

                    strSQL = @"Update #tmpDetectInfo Set DilutionFactor{0}=null where ID{0}='' and SickPersonID{0}=''";
                    strSQL = string.Format(strSQL, iCol);
                    dbcon.ExecuteSql(strSQL);

                    strSQL = "Update #tmpDetectInfo Set SickPersonName{0}=B.SickName From msickperson B where #tmpDetectInfo.SickPersonID{0}=B.SickRecID";
                    strSQL = string.Format(strSQL, iCol.ToString());
                    dbcon.ExecuteSql(strSQL);
                }
            }

            PrintInfo printInfo = new PrintInfo();
            Reports.Report rpt = new Reports.Report();
            rpt.OeDailyCashSalesPaymentReport(dbcon, printInfo, blnWithAll);

        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
           
        }

        private void 打印面板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                PrintRpt(dbcon, mlngRecID.ToString(),false);
            }
        }

        private void 打印检测结果ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                PrintRpt(dbcon, mlngRecID.ToString(), true);
            }
        }

      
       

        
    }
}
